package com.bbx.taxi.client.Activity.login;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.gclient.GClientBox;
import com.bbx.api.gclient.GMsg;
import com.bbx.api.sdk.SDK;
import com.bbx.api.sdk.model.base.BaseModel;
import com.bbx.api.sdk.model.comm.returns.Svconfigs;
import com.bbx.api.sdk.model.comm.returns.line.To_Cities;
import com.bbx.api.sdk.model.driver.DispatchOrderBuild;
import com.bbx.api.sdk.model.passanger.SvconfigBuild;
import com.bbx.api.sdk.model.passanger.Token;
import com.bbx.api.sdk.model.passanger.VersionBuild;
import com.bbx.api.sdk.model.passanger.Return.Version;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.config.conn.GetLineNet;
import com.bbx.api.sdk.net.config.conn.SvconfigNet;
import com.bbx.api.sdk.net.passeger.conn.TokenNet;
import com.bbx.api.sdk.net.passeger.conn.VersionNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.taxi.client.Task.MyServerTimeTask;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.MainActivity;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Guide.GuideActivity;
import com.bbx.taxi.client.Activity.Menu.SetActivity;
import com.bbx.taxi.client.Bean.City;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Extra.GuideMsg;
import com.bbx.taxi.client.DB.LineDB;
import com.bbx.taxi.client.DB.RecommenDB;
import com.bbx.taxi.client.Service.LoginService;
import com.bbx.taxi.client.Service.UpgradeService;
import com.bbx.taxi.client.Task.MyLineTask;
import com.bbx.taxi.client.Task.MyLineTask.OnLineFinishListener;
import com.bbx.taxi.client.UpdateChecker.UpdateCheck;
import com.bbx.taxi.client.UpdateChecker.UpdateCheck.OnUpdateListener;
import com.bbx.taxi.client.UpdateChecker.baidu.MyCPCheckUpdateCallback;
import com.bbx.taxi.client.UpdateChecker.baidu.MyCPCheckUpdateCallback.OnBaiduUpdateListener;
import com.bbx.taxi.client.UpdateChecker.qihoo.MyQihooUpdate;
import com.bbx.taxi.client.UpdateChecker.qihoo.MyQihooUpdate.OnQihooUpdateListener;
import com.bbx.taxi.client.UpdateChecker.ui.MyUpdateLoad;
import com.bbx.taxi.client.UpdateChecker.ui.MyUpdateLoad.UpdateType;
import com.bbx.taxi.client.Util.ChannelName;
import com.bbx.taxi.client.Util.DataCleanManager;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.NetworkDetector;
import com.bbx.taxi.client.Util.VersionInfo;
import com.bbx.taxi.client.Util.VersionUtils;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickLeftListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickRightListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickSingleListener;
import com.bbx.taxi.client.widget.StatusBar.StatusBar;
import com.umeng.analytics.MobclickAgent;

public class WelcomeActivity extends Activity implements OnUpdateListener,OnBaiduUpdateListener,OnQihooUpdateListener{
	private static final long SPLASH_DELAY_MILLIS = 3000;
	private final int GO_MAIN = 1000;
	private final int GO_GUIDE = 1001;
	private final int GO_LOGIN = 1002;
	private long starttime;
	private boolean isFirstIn = false;
	private Activity context;
	private MyApplication mApplication;
	public static  int platform;//0是帮邦行，2001是天山行，1001是公务车,泉州公务车3001
	List<City> cityList=new ArrayList<City>();
	UpdateCheck mUpdateCheck;
	 MyAlertDailog dialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_welcome);
		super.onCreate(savedInstanceState);
		ButterKnife.inject(this);
		//透明状态栏  
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);  
		//透明导航栏  
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); 
		context=this;
		mApplication=MyApplication.getInstance();
		initView();

	}
    @Override
    protected void onResume() {
    	// app 从后台唤醒，进入前台,不执行。
    	Value.isActive=true;
    	super.onResume();
    }
	protected void initView() {
		switch(VersionUtils.getVersionType(context)){
		case official_qz:
			platform=3001;
			break;
		case official:
			platform=1001;
			break;
		}
		MobclickAgent.updateOnlineConfig(this);
		dialog=new MyAlertDailog(this);
		starttime = DateFormat.getTime();
		mApplication.onStartLocation();
		mApplication.isFirstClient=true;
		SDK.VER=platform+"_"+ChannelName.getAppMetaData(this)+"_"+VersionInfo.getVersion(this);
		if(NetworkDetector.detect(this)){
			switch(Value.isMode){
			case Value.isNormal:
				mUpdateCheck=UpdateCheck.getInstance(this);
				mUpdateCheck.setOnUpdateListener(this,platform,ChannelName.getAppMetaData(this));
				break;
			case Value.isBaidu:
				//百度SDK
				MyCPCheckUpdateCallback mMyCPCheckUpdateCallback = new MyCPCheckUpdateCallback(context,null,UpdateType.TYPE_QIDONG);
				mMyCPCheckUpdateCallback.setOnBaiduUpdateListener(this);
				BDAutoUpdateSDK.cpUpdateCheck(this, mMyCPCheckUpdateCallback);;
				break;
			case Value.is360:
				MyQihooUpdate mMyQihooUpdate = new MyQihooUpdate(context,null,UpdateType.TYPE_QIDONG);
				mMyQihooUpdate.setOnQihooUpdateListener(this);
				mMyQihooUpdate.onStart();
				break;
			}
			
		}
		else{
			Toast.makeText(this,getResources().getString(R.string.no_network), Toast.LENGTH_SHORT).show();
			startActivity(2);
		}

	}
    public void getTime(){
    	MyServerTimeTask.getInstance(context);
    	startActivity(2);
    }
	/**
	 * 从Assets中读取图片
	 */
	private Bitmap getImageFromAssetsFile(String fileName) {
		Bitmap image = null;
		AssetManager am = getResources().getAssets();
		try {
			InputStream is = am.open(fileName);
			image = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return image;

	}
	/** 跳转类型0为引导页，1为登陆，2为主界面 */
	public void startActivity(int type) {
		isFirstIn = SharedPreUtil.getBooleanValue(this,
				SharedPreEncryptUtil.isFirstIn, true);
		if (isFirstIn) {
			type = 0;
		}
		long currentTime = DateFormat.getTime();
		long differTime = currentTime - starttime;
		if (differTime < SPLASH_DELAY_MILLIS) {
			switch (type) {
			case 0:
				mHandler.sendEmptyMessageDelayed(GO_GUIDE, SPLASH_DELAY_MILLIS
						- differTime);
				break;
			case 1:
				mHandler.sendEmptyMessageDelayed(GO_LOGIN, SPLASH_DELAY_MILLIS
						- differTime);
				break;
			case 2:
				mHandler.sendEmptyMessageDelayed(GO_MAIN, SPLASH_DELAY_MILLIS
						- differTime);
				break;
			}

		} else {
			// 时间已经超过3秒了，直接启动不等待
			switch (type) {
			case 0:
				mHandler.sendEmptyMessage(GO_GUIDE);
				break;
			case 1:
				mHandler.sendEmptyMessage(GO_MAIN);
				break;
			case 2:
				mHandler.sendEmptyMessage(GO_MAIN);
				break;
			}
		}
	}

	/**
	 * Handler:跳转到不同界面
	 */
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (isFinishing()) {
				return;
			}
			switch (msg.what) {
			case GO_GUIDE:
				startActivity(new Intent(WelcomeActivity.this,
						GuideActivity.class).putExtra(GuideMsg.extra_guide,
						GuideMsg.guide_welcome));
				break;
			case GO_LOGIN:
				startActivity(new Intent(WelcomeActivity.this,
						MainActivity.class));
				break;
			case GO_MAIN:
				startActivity(new Intent(WelcomeActivity.this,
						MainActivity.class));
				break;
			}
			finish();
			super.handleMessage(msg);
		}
	};

	protected void onDestroy() {
		if(mUpdateCheck!=null)
		mUpdateCheck.removeOnUpdateListener();
		super.onDestroy();

	}

	public void finish() {
		super.finish();
		overridePendingTransition(0, 0);
	}

	@Override
	public void onUpdateSuccess(Version version) {
		if(version.getforce_update()==1){//强制更新
			onShowForceUpdate(version);
		}
		else{
			onShowNoForceUpdate(version);
		}
	}

	@Override
	public void onUpdateFailed(int status,String msg) {
		getTime();
	}
	public void onShowForceUpdate(final Version version){
		String updatecontent=version.getDescription();
		dialog.setTitle(this.getResources().getString(R.string.mydailog_update_content));
		dialog.setContent2(updatecontent);
		dialog.setSingle(this.getResources().getString(R.string.mydailog_confirm_update));
		dialog.show();
		dialog.setOnClickSingleListener(new onClickSingleListener() {
			@Override
			public void onClickSingle() {
				dialog.dismiss();
				onUpdate(true,version);
			}
		});
	}
    /**
     * 弹出不强制更新
     */
    public void onShowNoForceUpdate(final Version version){
    	String updatecontent=version.getDescription();
    	dialog.setTitle(this.getResources().getString(R.string.mydailog_update_content));
    	dialog.setContent2(updatecontent);
    	dialog.setLeftButtonText(this.getResources().getString(R.string.mydailog_cancel_update));
		dialog.setRightButtonText(this.getResources().getString(R.string.mydailog_confirm_update));
		if (dialog != null && !dialog.isShowing()) {
			dialog.show();
		}
		dialog.setOnClickLeftListener(new onClickLeftListener() {	
			@Override
			public void onClickLeft() {
				dialog.dismiss();
				getTime();
			}
		});
		dialog.setOnClickRightListener(new onClickRightListener() {
			
			@Override
			public void onClickRight() {
				dialog.dismiss();
				onUpdate(false,version);
			}
		});
    }
    /** 
     * 更新
     * @param isForce 是否强制更新
     * @param url
     */
    public void onUpdate(boolean isForce,Version version){
    	MyUpdateLoad mMyUpdateLoad=new MyUpdateLoad();
		mMyUpdateLoad.downloadApk(context, isForce,UpdateType.TYPE_QIDONG,version.getURL(),version.getVersion());
		ToastUtil.showToast(this,R.string.downloading);
		if (isForce) {
			context.stopService(new Intent(context, LoginService.class));
		} else {
			getTime();

		}
    }
	@Override
	public void onBaiduUpdate() {
		getTime();
	}
	@Override
	public void onQihooUpdate() {
		getTime();
	}

}
